﻿using Application.DTO;
using Application.DTO.Dictionary;
using Application.IService.Dictionary;
using AutoMapper;
using Domain.Entity.Dictionary;
using Infrastructure.IRepository;
using Infrastructure.IRepository.Dictionary;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application.Service.Dictionary
{
    public class DictionaryValueService:BaseService<DictionaryValue>,IDictionaryValueService
    {
        private readonly IUnitOfWork unitOfWork;
        private readonly IDictionaryValueRepository dictionaryValueRepository;
        private readonly IMapper mapper;
        public DictionaryValueService(IUnitOfWork unitOfWork, IDictionaryValueRepository dictionaryValueRepository, IMapper mapper):base(unitOfWork,dictionaryValueRepository)
        {
            this.unitOfWork = unitOfWork;
            this.dictionaryValueRepository = dictionaryValueRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加字典项
        /// </summary>
        /// <param name="dtos">字典项集合</param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> InsertDictionaryValues(List<DictionaryValuesDTO> dtos)
        {
            using(IDbContextTransaction tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //将dto转为实体类型
                    List<DictionaryValue> list = mapper.Map<List<DictionaryValue>>(dtos);

                    //批量添加
                    await dictionaryValueRepository.InsertBatch(list);

                    //保存
                    int h = await unitOfWork.SaveChanges();

                    tran.Commit();
                    //返回
                    return new ResultDTO<string>("" + h, Domain.Enum.ResultStatusCode.SUCCESS, "添加字典项成功！！！");
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new ResultDTO<string>(ex.Message,Domain.Enum.ResultStatusCode.HANDLEFAIL,"未知错误！！！");
                }
            }
        }
        /// <summary>
        /// 修改字典项
        /// </summary>
        /// <param name="dtos">字典项集合</param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> UpdateDictionaryValues(List<DictionaryValuesDTO> dtos)
        {
           using(IDbContextTransaction tran = unitOfWork.GetDbContext().Database.BeginTransaction())
            {
                try
                {
                    //获取该表之前的字典从表数据信息中的ID
                    IEnumerable<int> valueIds = (await dictionaryValueRepository.GetAll()).AsNoTracking().Where(m => m.DicKeyId == dtos[0].DicKeyId && !m.IsDeleted).Select(m => m.Id);

                    //获取dto中待修改的字典从表数据中的ID
                    IEnumerable<int> detailIds = mapper.Map<List<DictionaryValue>>(dtos).Select(m => m.Id);

                    //比较修改的字典项在数据库是否存在，取存在的放到修改集合
                    IEnumerable<int> editValuesIds = detailIds.Intersect(valueIds);
                    //获取新增到的字典项
                    IEnumerable<int> addValuesIds = detailIds.Except(valueIds);
                    //获取删除项
                    IEnumerable<int> removeValuesIds = valueIds.Except(detailIds);

                    //将以上三个ID集合转为实体集合
                    List<DictionaryValue> editValues = await dictionaryValueRepository.GetDictionaryValueById(editValuesIds);
                    List<DictionaryValue> addValues = await dictionaryValueRepository.GetDictionaryValueById(addValuesIds);
                    List<DictionaryValue> removeValues = await dictionaryValueRepository.GetDictionaryValueById(removeValuesIds);

                    //批量修改字典从表信息
                    await dictionaryValueRepository.UpdateBatch(editValues);
                    await dictionaryValueRepository.InsertBatch(addValues);
                    await dictionaryValueRepository.DeleteBatch(removeValues);

                    //保存字典两表信息
                    int h = await unitOfWork.SaveChanges();

                    tran.Commit();
                    return new ResultDTO<string>(""+h, Domain.Enum.ResultStatusCode.SUCCESS, "修改字典集成功！！！");
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new ResultDTO<string>(ex.Message, Domain.Enum.ResultStatusCode.HANDLEFAIL, "未知错误！！！");
                }
            }
        }
        /// <summary>
        /// 删除字典项，采用逻辑删除
        /// </summary>
        /// <param name="ids">字典项的ID值集合</param>
        /// <returns></returns>
        public async Task<ResultDTO<string>> SoftDeleteDictionaryValues(string ids)
        {
            //分割id
            int[] idArray = Array.ConvertAll(ids.Split(','), int.Parse);

            List<DictionaryValue> list = new List<DictionaryValue>();
            //循环逻辑删除
            foreach (var item in idArray)
            {
                //查询字典是否存在
                var m = await dictionaryValueRepository.GetDictionaryValueById(item);
                if (m != null)
                {
                    m.IsDeleted = true;
                    list.Add(m);
                }
            }

            //批量修改字典数据
            await dictionaryValueRepository.UpdateBatch(list);

            //保存  
            int h = await unitOfWork.SaveChanges();

            return new ResultDTO<string>($"{h}", Domain.Enum.ResultStatusCode.SUCCESS, "删除成功");
        }
        /// <summary>
        /// 查询字典项
        /// </summary>
        /// <param name="key">字典键ID</param>
        /// <returns></returns>
        public async Task<ResultDTO<List<DictionaryValuesDTO>>> SearchDictionaryValues(int key)
        {
            var temp = await dictionaryValueRepository.GetDictionaryValueByKeyId(key);

            List<DictionaryValuesDTO> list = mapper.Map<List<DictionaryValuesDTO>>(temp);

            return new ResultDTO<List<DictionaryValuesDTO>>(list);
        }
    }
}
